//
//  OwnerCompleteViewController.m
//  Commerce
//
//  Created by xiaofeifei on 15/2/9.
//  Copyright (c) 2015年 fei. All rights reserved.
//

#import "OwnerCompleteViewController.h"
#import "GTMBase64.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"

@interface OwnerCompleteViewController (){
    NSArray *_specificationArray;
    NSArray *_typeArray;
    NSMutableArray *_photosList;
    NSString *_photosStr;
}

@end

@implementation OwnerCompleteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _photosList = [[NSMutableArray alloc] initWithCapacity:10];
    
    _specificationArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"SpecificationData"];
    _typeArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"TypeData"];
    if (_specificationArray.count == 0) {
        [self getSpecificationData];
    }
    if (_typeArray.count == 0) {
        [self getTypeData];
    }

    _specificationTextField.inputAccessoryView = _doneToolBar;
    _specificationTextField.inputView = _dataPicker;
    _typeTextField.inputAccessoryView = _doneToolBar;
    _typeTextField.inputView = _typeDataPicker;
    
    NSDictionary *userDic = [[GlobalData sharedGlobalData] userinfoDic];
    _specificationTextField.text = @"不限制";
    _typeTextField.text =@"不限制";
    _nameTextField.text = [userDic[@"TrueName"] isEqual:[NSNull null]]?@"":userDic[@"TrueName"];
    _addressTextField.text= [userDic[@"Address"] isEqual:[NSNull null]]?@"":userDic[@"Address"];
    _licensePlateTextField.text = [userDic[@"CarNo"] isEqual:[NSNull null]]?@"":userDic[@"CarNo"];
    _drivingLicenceTextField.text =[userDic[@"DrivingNo"] isEqual:[NSNull null]]?@"":userDic[@"DrivingNo"];
    
    // Do any additional setup after loading the view from its nib.
}


#pragma mark -请求接口
- (void)sendImage{
    if ([_photosList count] == 0) {
        _photosStr = @"";
        [self getCompleteUserInfo];
        return;
    }
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:10];
    for (int i ; i < [_photosList count]; i++) {
        NSMutableDictionary *parameters = [GlobalData paramterDic];
        UIImage *img =_photosList[i];
        NSData *data = UIImageJPEGRepresentation(img, 1);
        NSString *imageStr = [GTMBase64 stringByEncodingData:data];
        [parameters addEntriesFromDictionary:@{@"byte_str":imageStr,
                                               @"img_type":@"user",
                                               }];
        [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/upfile",URL_ROOT]
                                        params:parameters
                                   requestMode:DGHTTPMethodPOST
                                   loadingShow:YES
                                  didFinshLoad:^(id result) {
                                      id responseObject = result;
                                      [SVProgressHUD dismiss];
                                      NSLog(@"responseObject=%@",responseObject);
                                      [list addObject:responseObject[@"result"]];
                                      if (_photosStr.length == 0) {
                                          _photosStr =responseObject[@"result"];
                                      }else{
                                          _photosStr = [NSString stringWithFormat:@"%@@%@",_photosStr,responseObject[@"result"]];
                                      }
                                      if (list.count == _photosList.count) {
                                          [self getCompleteUserInfo];
                                      }

                                      
                                  }];

    }
}

- (void)getCompleteUserInfo{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSString *uid = [[GlobalData sharedGlobalData] userinfoDic][@"UserID"];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [parameters addEntriesFromDictionary:@{@"userid":uid,
                                           @"car_spec":_specificationTextField.text,
                                           @"car_type":_typeTextField.text,
                                           @"true_name":_nameTextField.text,
                                           @"address":_addressTextField.text,
                                           @"car_no":_licensePlateTextField.text,
                                           @"driving_no":_drivingLicenceTextField.text,
                                           @"user_pic":_photosStr
                                           }];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@user/userinfo",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  [SVProgressHUD dismiss];
                                  if (responseObject[@"result"]) {
                                      [SVProgressHUD showSuccessWithStatus:@"提交成功，等待管理员审核"];
                                      [self backBtnAct:nil];
                                  }else{
                                      [SVProgressHUD showInfoWithStatus:@"提交失败"];
                                  }
                              }];
}

- (void)getSpecificationData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/carspec",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  NSMutableArray *temp = [[NSMutableArray alloc] init];
                                  [temp addObject:@{@"Code":@"0",@"CodeID":@"0",@"CodeType":@"0",@"Text":@"不限制"}];
                                  [temp addObjectsFromArray:responseObject];
                                  _specificationArray = temp;
                                  [[NSUserDefaults standardUserDefaults] setObject:_specificationArray forKey:@"SpecificationData"];
                                  [SVProgressHUD dismiss];
                              }];
}

- (void)getTypeData{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/cartype",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  NSMutableArray *temp = [[NSMutableArray alloc] init];
                                  [temp addObject:@{@"Code":@"0",@"CodeID":@"0",@"CodeType":@"0",@"Text":@"不限制"}];
                                  [temp addObjectsFromArray:responseObject];
                                  _typeArray = temp;
                                  [[NSUserDefaults standardUserDefaults] setObject:_typeArray forKey:@"TypeData"];
                                  [SVProgressHUD dismiss];
                              }];
}

#pragma mark -IBAction
- (IBAction)doneSelect:(id)sender {
    if ([_specificationTextField isFirstResponder]) {
        _specificationTextField.text = [_specificationArray objectAtIndex:[_dataPicker selectedRowInComponent:0]][@"Text"];
        [_specificationTextField resignFirstResponder];
    }
    if ([_typeTextField isFirstResponder]) {
        _typeTextField.text = [_typeArray objectAtIndex:[_typeDataPicker selectedRowInComponent:0]][@"Text"];
        [_typeTextField resignFirstResponder];
    }
}

- (IBAction)saveUserInfo:(id)sender{
    if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
        [SVProgressHUD showInfoWithStatus:@"请先登录"];
    }
    else if (_licensePlateTextField.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请填写车牌号"];
    }
    else if (_nameTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写姓名"];
    }
    else if (_specificationTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写车辆规格"];
    }
    else if (_typeTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写车辆类型"];
    }
    else if (_drivingLicenceTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写驾驶证号"];
    }
    else if (_addressTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写联系地址"];
    }
    else{
        [self sendImage];
//        [self getCompleteUserInfo];
    }
}


- (IBAction)clearUserInfo:(id)sender{
    _licensePlateTextField.text = nil;
    _nameTextField.text = nil;
    _specificationTextField.text = nil;
    _typeTextField.text = nil;
    _drivingLicenceTextField.text = nil;
    _addressTextField.text = nil;
}

#pragma mark -点击图片
- (IBAction)headerBtnAct:(id)sender {
    UIActionSheet *sheet;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择",@"取消", nil];
    }
    else {
        
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",@"取消", nil];
    }
    
    [sheet showInView:self.view withCompletionHandler:^(NSInteger buttonIndex) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            switch (buttonIndex) {
                case 0:
                    // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                    
                case 1:
                    // 相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    // 取消
                    return;
            }
        }
        else {
            if (buttonIndex != 0) {
                
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        
        imagePickerController.delegate = self;
        
        imagePickerController.allowsEditing = NO;
        
        imagePickerController.sourceType = sourceType;
        
        [(UINavigationController *)self.view.window.rootViewController presentViewController:imagePickerController animated:YES completion:^{}];
        
    }];
    
    
    [sheet showInView:[(UINavigationController *)self.view.window.rootViewController view]];
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    image = [self useImage:image];
    
    [_photosList addObject:image];
    [self paretoImgs];
    //    _headData = [UIImageJPEGRepresentation(image, 0.5) retain];
    //    _headImg.image = image;
}

- (UIImage *)useImage:(UIImage *)image {
    //    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    // Create a graphics image context
    CGSize newSize = CGSizeMake(200, 200);
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    
    //    [pool release];
    return newImage;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}


- (void)paretoImgs{
    //拍照
    float width = 35;
    float height = 35;
    float origX = 0;
    float origY = (_ImgsScroll.frame.size.height-height)/2.0;
    float gapX = 13;
    for (int i=0; i<[_photosList count]; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(origX+(gapX+width)*i, origY, width, height)];
        imageView.image =_photosList[i];
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 3.0;
        // 事件监听
        imageView.tag = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)]];
        // 内容模式
        imageView.clipsToBounds = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [_ImgsScroll addSubview:imageView];
        
    }
    if (_photosList.count >= 4) {
        [_cameraBtn setHidden:YES];
    }else{
        [_cameraBtn setHidden:NO];
    }
    [_cameraBtn setFrame:CGRectMake(origX+(gapX+width)*[_photosList count] +5, _cameraBtn.frame.origin.y, _cameraBtn.frame.size.width, _cameraBtn.frame.size.height)];
    _ImgsScroll.contentSize = CGSizeMake(_photosList.count >= 4 ? origX+(gapX+width)*[_photosList count]:origX+(gapX+width)*[_photosList count]+45, _ImgsScroll.frame.size.height);
}

- (void)tapImage:(UITapGestureRecognizer *)tap {
    NSArray *imgurlArray = _photosList;
    
    int count = _photosList.count;
    // 1.封装图片数据
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++) {
        // 替换为中等尺寸图片
        //        NSString *url = imgurlArray[i];
        MJPhoto *photo = [[MJPhoto alloc] init];
        //        photo.placeholder = [_photosList objectAtIndex:i];
        //        photo.url = [NSURL URLWithString:url]; // 图片路径
        UIImageView *imageview = [[UIImageView alloc] initWithImage:[_photosList objectAtIndex:i]];
        //        [imageview sizeToFit];
        photo.srcImageView = imageview; // 来源于哪个UIImageView
        [photos addObject:photo];
    }
    
    // 2.显示相册
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = (tap.view.tag>=100)?(tap.view.tag-100):tap.view.tag; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    [browser show];
}

#pragma mark -
#pragma mark picker methods
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if ([_specificationTextField isFirstResponder]) {
        return _specificationArray.count;
    }
    return _typeArray.count;
}

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSString *title;
    if ([_specificationTextField isFirstResponder]) {
        title = [_specificationArray objectAtIndex:row][@"Text"];
    }else{
        title = [_typeArray objectAtIndex:row][@"Text"];
    }
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
